package com.lefull.lefullbase.utils.helper;

import android.content.Context;
import android.os.Looper;
import android.widget.Toast;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

/**
 * Created by Jack on 2016/9/9.
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {
    private final String TAG = CrashHandler.class.getSimpleName();
    private static Thread.UncaughtExceptionHandler defaultHandler = null;
    private Context context = null;

    public CrashHandler(Context context) {
        this.context = context;
    }

    public static void init(CrashHandler crashHandler) {
        defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(crashHandler);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        // 调用系统错误机制
        if (!handleException(ex) && defaultHandler != null) {
            //如果用户没有处理则让系统默认的异常处理器来处理
            defaultHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                L.info(TAG, ex.toString());
                L.info(TAG, getCrashDeviceInfo());
                L.info(TAG, getCrashInfo(ex));
            }
            //退出程序
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        //使用Toast来显示异常信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(context, "很抱歉,程序出现异常,即将退出...", Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }.start();

        return true;
    }

    /**
     * 获取应用崩溃的详细信息
     *
     * @param ex
     * @return
     */
    public String getCrashInfo(Throwable ex) {
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.setStackTrace(ex.getStackTrace());
        ex.printStackTrace(printWriter);
        return writer.toString();
    }

    public String getCrashDeviceInfo() {
        String versionName = DeviceUtil.getVersionName(context);
        String model = android.os.Build.MODEL;
        String androidVersion = android.os.Build.VERSION.RELEASE;
        String manufacturer = android.os.Build.MANUFACTURER;
        return versionName + "  " +
                model + "  " +
                androidVersion + "  " +
                manufacturer;
    }
}
